package com.itfreer.gis.data.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.springframework.stereotype.Component;

/**
 * Excel文件解释器
 */
@Component
public class ExcelFileDataEditServerImp implements ExcelFileDataEditServer {

	public static final Integer LIST_TYPE = 0;

	public static final Integer CARD_TYPE = 1;

	@SuppressWarnings("resource")
	@Override
	public List<SimpleFeature> queryFeature(String source, String where) throws Exception {
		// 打开指定位置的Excel文件
		FileInputStream file = new FileInputStream(new File(source));

		Workbook workbook = null;
		if (source.endsWith("xlsx")) {
			workbook = new XSSFWorkbook(file);
		} else {
			workbook = new HSSFWorkbook(file);
		}

		// 打开Excel中的第一个Sheet
		Sheet sheet = workbook.getSheetAt(0);
		List<String> colums = new ArrayList<String>();
		colums.add("XH");
		colums.add("X");
		colums.add("Y");
		colums.add("BH");

		List<SimpleFeature> lisGis = new ArrayList<>();
		List<Coordinate> points = new ArrayList<>();

		String bs = null;
		for (int k = 1; k <= sheet.getLastRowNum(); k++) { // 行元素
			Row row = sheet.getRow(k);
			String ibs = getCellValue(row.getCell(3)).toString();
			if (bs == null) {
				bs = ibs;
			}

			if (!bs.equals(ibs)) {
				SimpleFeature f = createFeature(points, k);
				if (f != null) {
					lisGis.add(f);
				}
				bs = ibs;
			}

			points.add(new Coordinate(Double.parseDouble(getCellValue(row.getCell(1)).toString()),
					Double.parseDouble(getCellValue(row.getCell(2)).toString())));

			if (k == sheet.getLastRowNum()) {
				SimpleFeature f = createFeature(points, k);
				if (f != null) {
					lisGis.add(f);
				}
			}
		}
		return lisGis;
	}

	private static SimpleFeature createFeature(List<Coordinate> points, int k)
			throws NoSuchAuthorityCodeException, FactoryException {
		// 一个点以内，不处理
		if (points.size() <= 1) {
			points.clear();
			return null;
		}
		// 检查最后一个点和第一个点是否一样
		Coordinate one = points.get(0);
		Coordinate last = points.get(points.size() - 1);
		if (one.getX() != last.getX() || one.getY() != last.getY()) {
			points.add(new Coordinate(one.getX(), one.getY()));
		}
		// 二个点以内，不处理
		if (points.size() <= 2) {
			points.clear();
			return null;
		}
		Coordinate[] ps = new Coordinate[points.size()];
		ps = points.toArray(ps);
		points.clear();
		return createFeature(ps, k);
	}

	private static SimpleFeature createFeature(Coordinate[] coords, Integer i)
			throws NoSuchAuthorityCodeException, FactoryException {
		GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
		LinearRing ring = geometryFactory.createLinearRing(coords);
		LinearRing holes[] = null; // use LinearRing[] to represent holes
		Polygon polygon = geometryFactory.createPolygon(ring, holes);

		SimpleFeatureType type = createFeatureType();
		// create the builder
		SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
		// add the values
		builder.add(polygon);
		// build the feature with provided ID
		SimpleFeature feature = builder.buildFeature("fid." + i.toString());
		return feature;
	}

	private static SimpleFeatureType createFeatureType() throws NoSuchAuthorityCodeException, FactoryException {
		// 定义图形信息和属性信息
		SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
		// CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
		// tb.setCRS(crs);
		tb.setName("shapefile");
		tb.add("the_geom", Polygon.class);
		// build the type
		final SimpleFeatureType ftype = tb.buildFeatureType();
		return ftype;
	}

	/**
	 * 获取列值
	 * 
	 * @param cell
	 * @return
	 */
	private static Object getCellValue(Cell cell) {
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_STRING:
			return cell.getRichStringCellValue().getString();
		case Cell.CELL_TYPE_NUMERIC:
			if (DateUtil.isCellDateFormatted(cell)) {
				return cell.getDateCellValue();
			} else {
				return cell.getNumericCellValue();
			}
		case Cell.CELL_TYPE_BOOLEAN:
			return cell.getBooleanCellValue();
		case Cell.CELL_TYPE_FORMULA:
			return cell.getCellFormula();
		case Cell.CELL_TYPE_BLANK:
			return "";
		}
		return "";
	}
	
	/**
	 * 查询
	 * @return
	 */
	@Override
	public List<SimpleFeature> queryFeature(String source, String option, Geometry geometry) throws Exception {
		return null;
	}
	
	@Override
	public Boolean addFeatures(String source, List<SimpleFeature> datas, SimpleFeatureType metadata)
			throws IOException, NoSuchAuthorityCodeException, FactoryException {
		return false;
	}

	@Override
	public SimpleFeature updateFeature(String source, SimpleFeature row, SimpleFeatureType metadata) {
		return row;
	}

	@Override
	public Boolean deleteFeature(String source, String where) throws Exception {
		return false;
	}

	@Override
	public SimpleFeatureType getTableMetadata(String tableName) {
		return null;
	}
}